package com.example.lastwork2.fragments.detail;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.lastwork2.MainActivity;
import com.example.lastwork2.R;
import com.example.lastwork2.adapter.OrderAdapter;
import com.example.lastwork2.fragments.OrderFragment;
import com.example.lastwork2.model.Shop;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class ShopDetailActivity extends AppCompatActivity {

    private ImageView shopIcon;
    private TextView shopName;
    private TextView shopBrief;
    private TextView shopPrice;
    private Button btnBuy;
    private Button addCart;

    private Shop shop;

    //存储订单中的商品信息
    private List<Shop> orderShop;
    //使用全局变量存储购物车信息
    public  static List<Shop> cartShop;
    //使用全局变存储购物车商品列表及所对应的商品数量    (方便后期进行计算总价格)
    public  static List<Integer> curnum;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);


        //获取控件
        getViews();

        //获取intent对象
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("obj");
        shop = (Shop) bundle.getSerializable("shop");
        //显示数据到对应控件
        showViews();


        //点击购买弹窗购买成功，并创建订单
        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗购买成功
                new AlertDialog.Builder(ShopDetailActivity.this)
                        .setMessage("购买成功")
                        .show();

                //创建新订单放到订单页面,连接数据库，创建新订单，将订单中的商品信息传入服务器
                orderShop = new ArrayList<>();
                orderShop.add(shop);
                sendOrderToServer(orderShop);






            }
        });


        //点击加入购物车    将此商品信息存储LIst集合
        addCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将当前商品加入cartShop，添加是去重
                int flag = 0;
                for(Shop shop1 : cartShop){
                    if (shop.getShopId() == shop1.getShopId()){
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0){
                    cartShop.add(shop);
                    curnum.add(1);
                    //将购物车数据和商品对应数量发送到数据库
                    sendCartToServer(cartShop,curnum);
                }
                //弹窗提示加入购物车成功

                new AlertDialog.Builder(ShopDetailActivity.this)
                        .setMessage("加入购物车成功")
                        .show();


            }
        });






    }


    //将购物车数据和商品对应数量发送到数据库
    private void sendCartToServer(List<Shop> cartShop, List<Integer> curnum) {
        String url1 = "http://10.0.2.2:8080/bigwork/cart";

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();

                    HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();
                    connection.setRequestMethod("POST");
                    //向服务器发送json数据
                    OutputStream os = connection.getOutputStream();
                    //发送cartShop数据
                    String jsonData = gson.toJson(cartShop);
                    os.write(jsonData.getBytes());
                    os.flush();
                    //发送curnum数据
                    String jsonCurnum = gson.toJson(curnum);
                    os.write(jsonCurnum.getBytes());
                    os.flush();
                    //发送userId
                    String jsonUserId = gson.toJson(MainActivity.userId);
                    os.write(jsonUserId.getBytes());
                    os.flush();
                    os.close();

                    //接受服务器传来的数据
                    InputStream inputStream = connection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();



    }

    //数据库中创建订单
    private void sendOrderToServer(List<Shop> orderShop) {

        String url1 = "http://10.0.2.2:8080/bigwork/order";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
                    String jsonData = gson.toJson(orderShop);

                    HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();
                    connection.setRequestMethod("POST");
                    //向服务器发送json数据
                    OutputStream os = connection.getOutputStream();
                    os.write(jsonData.getBytes());
                    os.flush();

                    String jsonUserId = gson.toJson(MainActivity.userId);
                    os.write(jsonUserId.getBytes());
                    os.flush();

                    os.close();

                    //接受服务器传来的数据
                    InputStream inputStream = connection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();
        //开启子线程连接服务器
        // 使用json将orderShop 发送过去
        //接收服务器返回的数据




    }

    private void showViews() {
        Glide.with(this)
                .load(shop.getIcon())
                .into(shopIcon);
        shopName.setText(shop.getShopName());
        shopBrief.setText(shop.getShopBrief());
        String price = String.valueOf(shop.getPrice());
        shopPrice.setText("￥"+price);


    }

    private void getViews() {
        shopIcon = findViewById(R.id.sp_icon);
        shopName = findViewById(R.id.sp_name);
        shopBrief = findViewById(R.id.sp_brief);
        shopPrice = findViewById(R.id.sp_price);
        btnBuy = findViewById(R.id.btn_buy);
        addCart = findViewById(R.id.btn_add_cart);


    }
}